package com.roncoo.pay.permission.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roncoo.pay.common.core.enums.PublicStatusEnum;
import com.roncoo.pay.common.core.page.PageBean;
import com.roncoo.pay.common.core.page.PageParam;
import com.roncoo.pay.permission.entity.PmsUser;
import com.roncoo.pay.permission.entity.PmsUserRole;
import com.roncoo.pay.permission.repository.PmsUserRepository;
import com.roncoo.pay.permission.repository.PmsUserRoleRepository;
import com.roncoo.pay.permission.service.PmsUserService;

/**
 * 操作员service接口实现
 *
 */
@Service("pmsUserService")
public class PmsUserServiceImpl implements PmsUserService {
	@Autowired
	private PmsUserRepository pmsUserRepository;

	@Autowired
	private PmsUserRoleRepository pmsUserRoleRepository;

	/**
	 * 创建pmsOperator
	 */
	public void saveData(PmsUser pmsOperator) {
		pmsUserRepository.save(pmsOperator);
	}

	/**
	 * 修改pmsOperator
	 */
	public void updateData(PmsUser pmsOperator) {
		pmsUserRepository.save(pmsOperator);
	}

	/**
	 * 根据id获取数据pmsOperator
	 * 
	 * @param id
	 * @return
	 */
	public PmsUser getDataById(String id) {
		return pmsUserRepository.findOne(id);

	}

	/**
	 * 分页查询pmsOperator
	 * @param pageParam
	 * @param ActivityVo PmsOperator
	 * @return
	 */
	public PageBean<PmsUser> listPage(PageParam pageParam, PmsUser pmsUser) {
		
		Pageable pageable = new PageRequest(pageParam.getPageNum(), pageParam.getNumPerPage());
		
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching(); //构建对象
        if(StringUtils.isNotEmpty(pmsUser.getLoginName())){
        	matcher.withMatcher("loginName", GenericPropertyMatchers.storeDefaultMatching());
        }else{
        	pmsUser.setLoginName(null);;
        }
        
        if(StringUtils.isNotEmpty(pmsUser.getRealName())){
        	matcher.withMatcher("realName", GenericPropertyMatchers.startsWith());
        }else{
        	pmsUser.setRealName(null);
        }
        
        if(StringUtils.isNotEmpty(pmsUser.getStatus())){
        	matcher.withMatcher("status", GenericPropertyMatchers.storeDefaultMatching()); 
        }else{
        	pmsUser.setStatus(null);
        }
        matcher.withIgnorePaths("version");
        pmsUser.setCreater(null);
        pmsUser.setCreateTime(null);
        pmsUser.setEditor(null);
        pmsUser.setEditTime(null);
        pmsUser.setRemark(null);
        pmsUser.setStatus(null);
        pmsUser.setId(null);
        pmsUser.setLoginPwd(null);
        pmsUser.setMobileNo(null);
        pmsUser.setRemark(null);
        pmsUser.setRoles(null);
        pmsUser.setSalt(null);
        pmsUser.setType(null);
        //创建实例
        Example<PmsUser> ex = Example.of(pmsUser, matcher); 
		
        Page<PmsUser> page = pmsUserRepository.findAll(ex, pageable);
		PageBean<PmsUser> pb = new PageBean<PmsUser>(page.getNumber(), page.getSize(), page.getTotalPages(),page.getContent());
		return pb;
	}

	/**
	 * 根据ID删除一个操作员，同时删除与该操作员关联的角色关联信息. type="1"的超级管理员不能删除.
	 * 
	 * @param id
	 *            操作员ID.
	 */
	public void deleteOperatorById(String operatorId) {
		PmsUser pmsOperator = pmsUserRepository.findOne(operatorId);
		if (pmsOperator != null) {
			if ("admin".equals(pmsOperator.getType())) {
				throw new RuntimeException("【" + pmsOperator.getLoginName() + "】为超级管理员，不能删除！");
			}
			pmsUserRepository.delete(operatorId);
			// 删除原来的角色与操作员关联
			pmsUserRoleRepository.deleteByUserId(operatorId);
		}
	}

	/**
	 * 更新操作员信息.
	 * 
	 * @param operator
	 */
	public void update(PmsUser operator) {
		pmsUserRepository.save(operator);
	}

	/**
	 * 根据操作员ID更新操作员密码.
	 * 
	 * @param operatorId
	 * @param newPwd
	 *            (已进行SHA1加密)
	 */
	public void updateOperatorPwd(String operatorId, String newPwd) {
		PmsUser pmsOperator = pmsUserRepository.findOne(operatorId);
		pmsOperator.setLoginPwd(newPwd);
		pmsUserRepository.save(pmsOperator);
	}

	/**
	 * 根据登录名取得操作员对象
	 */
	public PmsUser findOperatorByLoginName(String loginName) {
		return pmsUserRepository.findByLoginName(loginName);
	}

	/**
	 * 保存操作員信息及其关联的角色.
	 * 
	 * @param pmsOperator
	 *            .
	 * @param roleOperatorStr
	 *            .
	 */

	@Transactional
	public void saveOperator(PmsUser pmsOperator, String roleOperatorStr) {
		// 保存操作员信息
		pmsUserRepository.save(pmsOperator);
		// 保存角色关联信息
		if (StringUtils.isNotBlank(roleOperatorStr) && roleOperatorStr.length() > 0) {
			saveOrUpdateOperatorRole(pmsOperator, roleOperatorStr);
		}
	}

	/**
	 * 保存用户和角色之间的关联关系
	 */
	private void saveOrUpdateOperatorRole(PmsUser pmsUser, String roleIdsStr) {
		// 删除原来的角色与操作员关联
		List<PmsUserRole> listPmsOperatorRoles = pmsUserRoleRepository.findByUserId(pmsUser.getId());
		Map<String, PmsUserRole> delMap = new HashMap<String, PmsUserRole>();
		for (PmsUserRole pmsOperatorRole : listPmsOperatorRoles) {
			delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole);
		}
		if (StringUtils.isNotBlank(roleIdsStr)) {
			// 创建新的关联
			String[] roleIds = roleIdsStr.split(",");
			for (int i = 0; i < roleIds.length; i++) {
				String roleId = roleIds[i];
				if (delMap.get(roleId) == null) {
					PmsUserRole pmsOperatorRole = new PmsUserRole();
					pmsOperatorRole.setUserId(pmsUser.getId());
					pmsOperatorRole.setRoleId(roleId);
					pmsOperatorRole.setCreater(pmsUser.getCreater());
					pmsOperatorRole.setCreateTime(new Date());
					pmsOperatorRole.setStatus(PublicStatusEnum.ACTIVE.name());
					pmsUserRoleRepository.save(pmsOperatorRole);
				} else {
					delMap.remove(roleId);
				}
			}
		}

		Iterator<String> iterator = delMap.keySet().iterator();
		while (iterator.hasNext()) {
			String roleId = iterator.next();
			pmsUserRoleRepository.deleteByRoleIdAndUserId(roleId, pmsUser.getId());
		}
	}

	/**
	 * 修改操作員信息及其关联的角色.
	 * 
	 * @param pmsOperator
	 *            .
	 * @param roleOperatorStr
	 *            .
	 */
	public void updateOperator(PmsUser pmsOperator, String roleOperatorStr) {
		pmsUserRepository.save(pmsOperator);
		// 更新角色信息
		this.saveOrUpdateOperatorRole(pmsOperator, roleOperatorStr);
	}
}
